import {Command} from '../constant';
import Taro from '@tarojs/taro';
import {Dispatch} from 'typings';
import {IAllReducerProps} from '../types';
import {getReducerData} from '@/redux/store';
import {extraPathsValue} from '@/redux/util';
import api from 'api';

export default (dispatch: Dispatch) => {
  let action = {
    commonChange(...param: any) {
      dispatch({
        type: Command.commonChange,
        payload: extraPathsValue(...arguments),
      });
    },
    async getPostList(curNow) {
      let {pageNum, totalPages, myPostList} = getData().main;
      let selectDistance = Taro.getStorageSync('selectDistance');
      let {user} = Taro.getStorageSync('b2b-wechat@login');
      let params, result;
      action.commonChange('main.isLoading', true);
      if (curNow == 0) {
        //我的发布
        params = {
          publishUser: user?.id || '',
          pageNum: pageNum,
          communityCode: selectDistance.code,
        };
        result = await api.forumController.findMyPublishForum(params);
      } else if (curNow == 1) {
        //我的赞
        params = {
          userId: user.id,
          communityCode: selectDistance.code,
        };
        result = await api.forumController.findMyThumbForum(params);
      } else if (curNow == 2) {
        //我的评论
        params = {
          userId: user.id,
          pageNum: pageNum,
        };
        result = await api.forumController.findMyCommentForum(params);
      }
      if (result.code == '200') {
        action.commonChange('main.isLoading', false);
        if (curNow == 1) {
          //赞,不分页
          action.commonChange('main.myPostList', result?.data ? result.data : []);
        } else {
          if (pageNum == 1) {
            action.commonChange('main.myPostList', result?.data?.rows);
            action.commonChange('main.totalPages', result?.data?.totalPage);
          } else {
            let newList = myPostList.concat(result?.data?.rows);
            action.commonChange('main.myPostList', newList);
            action.commonChange('main.totalPages', result?.data?.totalPage);
          }
        }
      }
    },
    async addThumb(params) {
      await api.forumController.addThumb(params);
    },
    async deleteThumb(params) {
      await api.forumController.deleteThumb(params);
    },
  };

  return action;
};

function getData(): IAllReducerProps {
  return {
    main: getReducerData('packageCMyPostMain'),
  };
}

//create by moon https://github.com/creasy2010/moon
